var $api = require('../../utils/api.js'); //引入api.js页面  
Page({
    data: {
        //判断小程序的API，回调，参数，组件等是否在当前版本可用。
        tags: {},
        tagIsHide: false, //是否隐藏搜索tag
        tagShow: false, //是否关闭tag标签
        isRegistered: false, //判断用户是否注册
        searchTag: "", //搜索tag名称
        sortValue: 0, //排序下拉框选择的值
        sortOption: [
            {
                text: '默认排序',
                value: ''
            },
            {
                text: '价格从低到高排列',
                value: 1
            },
            {
                text: '价格从高到低排列',
                value: 2
            },
            {
                text: '按时间降序排序',
                value: 3
            },
            {
                text: '按时间升序排序',
                value: 4
            },
        ], //排序下拉框选项
        priceValue: "不限", //价格下拉框选择的值
        priceOption: ["不限", "5万以下", "5-10万", "10-15万", "15-30万", "30万以上"], //价格下拉选项
        sliderValue: 100, //价格slider百分比
        carSource: [], //车源列表
        nowpage: 1, //列表页码
        isHideLoadMore: true, //下拉加载
        noMore: true, //没有更多数据提示
        //搜索
        name: '', //车辆名字
        carCity: '', //车辆城市
        brandName: '', //品牌名称
        brandId: '', //品牌ID
        vehicleType: '', //车辆类型
        price: '', //车辆价格
        carAge: '', //车龄
        carDisplacement: '', //汽车排量
        showMileage: '', //汽车里程数
        country: '', //国别
        gearbox: '', //变速箱
        color: '', //车辆颜色

        //搜索
        brandName: '',
        vehicleType2: '',
        price2: '',
        carAge2: '',
        carDisplacement2: '',
        showMileage2: '',
        country2: '',
        gearbox2: '',
        color2: '',
    },

    onLoad: function (query) {
        var that = this;
        const scene = decodeURIComponent(query.scene) ? decodeURIComponent(query.scene) : (decodeURIComponent(query.userId) ? decodeURIComponent(query.userId):  null);
        console.log(scene);
        //登录
        that.login(scene);

        //清空筛选
        var init = {
            vehicleType: "不限", //车辆选中的值
            priceValue: "不限", //价格
            carAge: "不限", //车龄
            mileage: "不限", //里程
            country: "不限", //国别
            carSourceLabel: "不限", //车源
            gearbox: "不限", //变速箱
            color: "不限", //车身颜色
            _vehicleType: '', //车辆类型
            _price: '', //车辆价格
            _carAge: '', //车龄
            _carDisplacement: '', //汽车排量
            _showMileage: '', //汽车里程数
            _country: '', //国别
            _gearbox: '', //变速箱
            _color: '', //车辆颜色
            carAgeSlider: 100, //车龄slider百分比
            displacementSlider: 100, //排量slider百分比
            sliderValue: 100, //价格slider百分比
            mileageSlider: 100, //里程slider百分比
        };
        wx.setStorageSync('filterData', init)
    },

    onShow: function () {
        if (wx.getStorageSync('token') == '') {
            this.login(null);
        } else {
            //获取userInfo
            $api.userInfo().then(res => {
                if (res.code == 1) {
                    wx.setStorageSync('userInfo', res.data);
                    wx.setStorageSync('user_phone', res.data.mobile);
                    wx.setStorageSync('vip_time_status', res.data.vip_time_status);
                    wx.setStorageSync('vip_time', res.data.vip_time);
                    if (res.data.id_img) {
                        wx.setStorageSync('isRegistered', true)
                    } else {
                        wx.setStorageSync('isRegistered', false)
                    }
                    this.setData({
                        isRegistered: wx.getStorageSync('isRegistered'),
                        vip_time_status: res.data.vip_time_status,
                        vip_time: res.data.vip_time,
                    })
                }
            })
        }
        //判断用户是否注册、会员
        this.setData({
            isRegistered: wx.getStorageSync('isRegistered'),
            vipTimeStatus: wx.getStorageSync('vip_time_status'),
        })
        this.setTags();
        this.getUserCity();
        this.getGoodsList();
    },

    //登录
    login: function (scence) {
        var that = this;
        wx.login({
            success: res => {
                wx.setStorageSync('code', res.code);
                // 传给后台，再经过解析获取用户的 openid获取token
                let param = {
                    code: res.code,
                    Invitees: scence
                }
                console.log(param);
                $api.getLogin(param).then(res => {
                    if (res.code == 1) {
                        wx.setStorageSync('token', res.data.token);
                        wx.setStorageSync('openid', res.data.openid);
                        wx.showLoading({
                            title: '加载中',
                        })
                        //获取userInfo
                        $api.userInfo(param).then(res => {
                            if (res.code == 1) {
                                wx.setStorageSync('userInfo', res.data);
                                wx.setStorageSync('user_phone', res.data.mobile);
                                wx.setStorageSync('vip_time_status', res.data.vip_time_status);
                                wx.setStorageSync('vip_time', res.data.vip_time);
                                if (res.data.id_img) {
                                    wx.setStorageSync('isRegistered', true)
                                } else {
                                    wx.setStorageSync('isRegistered', false)
                                }
                                this.setData({
                                    isRegistered: wx.getStorageSync('isRegistered'),
                                    vip_time_status: res.data.vip_time_status,
                                    vip_time: res.data.vip_time,
                                })
                            }
                        })
                        wx.hideLoading()
                        //加载首页数据
                        //  that.getGoodsList();


                        //查看是否授权
                        wx.getSetting({
                            success: function (res) {
                                // 授权用户信息
                                if (res.authSetting['scope.userInfo']) {
                                    wx.getUserInfo({
                                        lang: 'zh_CN',
                                        success: function (res) {
                                            if (!wx.getStorageSync('city')) {
                                                that.setData({
                                                    city: res.userInfo.city,
                                                    carCity: res.userInfo.city
                                                })
                                                wx.setStorageSync("city", res.userInfo.city);
                                            }
                                        }
                                    })
                                }
                            }
                        });
                    }
                })
            }
        });
    },

    //获取用户信息，判断用户是否已经注册
    //获取用户地理信息
    getUserCity: function () {
        if (wx.getStorageSync("city") == "") {
            let userInfo = wx.getStorageSync('userInfo')
            this.setData({
                city: userInfo.city,
                carCity: userInfo.city
            });
        } else {
            this.setData({
                city: wx.getStorageSync("city"),
                carCity: wx.getStorageSync("city")
            })
        }
    },

    setTags: function () {
        var params = [{
                "key": "name",
                "value": this.data.name,
                'index': ''
            },
            // {
            //     "key": "city",
            //     "value": this.data.carCity,
            //     'index': ''
            // },
            {
                "key": "brand_id",
                "value": this.data.brandName,
                'index': 'brandName'
            },
            {
                "key": "vehicleType",
                "value": this.data.vehicleType2,
                'index': 'vehicleType2'
            },
            {
                "key": "price",
                "value": this.data.priceValue,
                'index': 'priceValue'
            },
            // {"key":"priceValue","value": this.data.priceValue},
            {
                "key": "carAge",
                "value": this.data.carAge2,
                'index': 'carAge2'
            },
            {
                "key": "carDisplacement",
                "value": this.data.carDisplacement,
                'index': 'carDisplacement'
            },
            {
                "key": "mileage",
                "value": this.data.showMileage2,
                'index': 'showMileage2'
            },
            {
                "key": "country",
                "value": this.data.country2,
                'index': 'country2'
            },
            {
                "key": "gearbox",
                "value": this.data.gearbox2,
                'index': 'gearbox2'
            },
            {
                "key": "color",
                "value": this.data.color2,
                'index': 'color2'
            }
        ];
        this.setData({
            'tags': params
        });
    },

    //获取商品列表
    getGoodsList: function () {
        let pageIndex = this.data.nowpage
        let param = {
            nowpage: this.data.nowpage,
            name: this.data.name,
            city: this.data.carCity == '全国' ? '' : this.data.carCity,
            brand_id: this.data.brand_id,
            vehicle_type: this.data.vehicleType,
            price: this.data.price,
            car_age: this.data.carAge,
            car_displacement: this.data.carDisplacement,
            show_mileage: this.data.showMileage,
            country: this.data.country,
            gearbox: this.data.gearbox,
            color: this.data.color,
            paixu_status: this.data.sort
        }
        $api.getGoodsList(param).then(res => {
            console.log(res);
            if (res.code == 1) {
                if (pageIndex > 1) {
                    var listBefore = this.data.carSource;
                    var currentList = res.data.list;
                    this.setData({
                        carSource: listBefore.concat(currentList),
                        isHideLoadMore: true,
                        noMore: (this.data.nowpage + 1) >= res.data.sum_page ? false : true
                    })
                } else {
                    this.setData({
                        carSource: res.data.list,
                        isHideLoadMore: true,
                        noMore: (this.data.nowpage + 1) >= res.data.sum_page ? false : true
                    })
                }
            }
        })
    },



    //选择排序下拉菜单后执行的方法
    sortEvent: function (e) {
        console.log(e.detail);
        // let sort = e.currentTarget.dataset.sort;
        //todo
        this.setData({
            sort: e.detail,
        })
        this.getGoodsList();
    },

    //价格下拉菜单选中后执行的方法
    priceEvent: function (e) {
        let priceText = e.currentTarget.dataset.price;
        let price = '';
        switch (priceText) {
            case '不限':
                price = '';
                break;
            case '5万以下':
                price = '0,5';
                break;
            case '5-10万':
                price = '5,10';
                break;
            case '10-15万':
                price = '10,15';
                break;
            case '15-30万':
                price = '15,30';
                break;
            case '30万以上':
                price = '30w_up';
                break;
        }

        this.setData({
            priceValue: priceText,
            price: price,
            sliderValue: 100
        })
        this.selectComponent("#price").toggle();
        this.setTags();
        this.getGoodsList();
    },

    //自定义价格滚动条拖动方法
    onDrag: function (event) {
        if (event.detail.value != 100) {
            this.setData({
                priceValue: '0-' + event.detail.value + '万',
                sliderValue: event.detail.value,
            });
        } else {
            this.setData({
                priceValue: "不限",
                sliderValue: 100
            });
        }
    },

    //确认选择自定义价格
    sumbitPrice: function () {
        let priceText = this.data.sliderValue;
        this.setData({
            sliderValue: priceText,
        });

        if (priceText == 100) {
            this.setData({
                price: '',
            });
        } else {
            this.setData({
                price: '0,' + priceText,
            });
        }
        // if (0 <= priceText && priceText <= 20) {
        //     this.setData({
        //         price: 0.5 * priceText + ',' + '10',
        //     });
        // } else if (20 < priceText && priceText <= 40) {
        //     this.setData({
        //         price: 0.5 * priceText + ',' + '20',
        //     });
        // } else if (40 < priceText && priceText <= 60) {
        //     this.setData({
        //         price: 0.5 * priceText + ',' + '30',
        //     });
        // } else if (60 < priceText && priceText <= 80) {
        //     this.setData({
        //         price: 0.5 * priceText + ',' + '40',
        //     });
        // } else if (80 < priceText && priceText < 100) {
        //     this.setData({
        //         price: 0.5 * priceText + ',' + '99999',
        //     });
        // } else {
        //     this.setData({
        //         price: '',
        //     });
        // }
        this.selectComponent("#price").toggle();
        this.setTags();
        this.getGoodsList();
    },

    openVehicleDetails: function (event) {
        let userInfo = wx.getStorageSync('userInfo')
        let vehicleId = event.currentTarget.dataset.vehicleid;
        if (this.data.isRegistered || userInfo.visit_time<5) {
            wx.navigateTo({
                url: '/pages/index/vehicleDetails?vehicleId=' + vehicleId,
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '注册会员查看更多信息',
                success: (res => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/my/registered'
                        })
                    }
                })
            })
        }
    },

    //标签关闭的方法
    closeTag: function (event) {
        const key = event.currentTarget.dataset.key;
        const index = event.currentTarget.dataset.index;
        if (index) {
            this.setData({
                [key]: '',
                [index]: '',
            });
        } else {
            this.setData({
                [key]: '',
            });
        }
        const filterData = wx.getStorageSync('filterData');
        if (key == "carAge") {
            filterData['carAge'] = "不限";
            filterData['carAgeSlider'] = 100;
            filterData['_carAge'] = "";
        } else if (key == "mileage") {
            filterData['mileage'] = "不限";
            filterData['mileageSlider'] = 100;
            filterData['_showMileage'] = "";
        } else if (key == "carDisplacement") {
            filterData['displacementSlider'] = 100;
            filterData['_carDisplacement'] = "";
        } else {
            //_key变量是筛选组件中选项所选中的值
            const _key = "_" + key;
            filterData[key] = "不限";
            filterData[_key] = "";
        }

        wx.setStorageSync('filterData', filterData);

        this.setTags();
        this.getGoodsList();
    },

    //下拉加载
    onReachBottom: function () {
        var that = this;
        if (this.data.noMore) {
            this.setData({
                isHideLoadMore: false,
                nowpage: nowpage + 1,
                noMore: true
            })
            setTimeout(function () {
                that.getGoodsList();
            }, 1000);
        }
    },

    //获取求购城市参数
    getBuyingParam() {
        if (wx.getStorageSync('carCity') != '') {
            this.setData({
                carCity: wx.getStorageSync('carCity')
            })
        }
    },

    //获取求购搜索栏参数
    getSearchTag() {
        let searchArray = wx.getStorageSync('searchArray');
        if (searchArray != '') {
            this.setData({
                searchTag: searchArray.searchTag,
                name: searchArray.name,
                tagIsHide: searchArray.tagIsHide,
                tagShow: searchArray.tagShow
            })
        }
        wx.removeStorageSync('searchArray');
    },


    // //重置
    // restAll: function () {

    // }
})